var t = getApp();
var app=getApp();
const infoconfig= require('../../utils/als_config');
var Poster =require('../../poster.js');
Page({
    data: {
        default_img:'http://bmobfile.twho.top/2020/04/17/2a60bcae4049592f80a057b06e205801.png',
        hidden:true,
        hasnewmore:true,
        hasmore:true,
        skip:1,
        newskip:1,
        nick_name:'',
        posterConfig:{},
        myavatar:'',
        votes:[],
        answerImg:[],
        allImg:[],
        agreeNumber:"20%",
        disagreeNumber:"80%",
        userChoose:1,
        loading:true,
        answer:[],
         isMonth:true,
         toplist:[],
         toplist2:[],
         info:'',
    },
    onLoad: function(t) {
        var uid=wx.getStorageSync('uid')
        if(uid){
            this.allRequest(1)
        }
    },
    onShow: function() {
        this.setData({
            nick_name: wx.getStorageSync('nickName'),
            myavatar:wx.getStorageSync('uimg')
        })
       
    },

     showMonth(e){
    let type=e.currentTarget.dataset.type
    console.log(type)
    if(type==2){
    var  isMonth= !1
 
    if(this.data.toplist.length==0){
    let newskip=this.data.newskip
      this.allRequest(newskip,2)
         this.setData({
      isMonth: isMonth,
   
    })
    }else{
      this.setData({
      isMonth: isMonth,
  
    toplist:this.data.toplist
    })
    }
   
    }else{
      var  isMonth= !0
  

        this.setData({
      isMonth: isMonth,
   
      votes:this.data.votes
    })
    }
  
  },
         showImg(t){
        var e = t.currentTarget.dataset.url;
       
        if(!e){return}
        wx.previewImage({
            current: e,
            urls: [ e ]
        });
    },
    targetToVoteDetail(t){
        var e = t.currentTarget.dataset.voteid;
        var type=t.currentTarget.dataset.type
        
        if(!e){return}
        if(type==2){
            wx.navigateTo({
            url: "../../more/newvote/detail?tid=" + e,
            success: function(t) {
                console.log(t);
            }
        });
        }else{
        wx.navigateTo({
            url: "../own_vote/detail?tid=" + e,
            success: function(t) {
                console.log(t);
            }
        });
        }
    },
    onReachBottom: function() {
        var t=this
        var e = t.data.skip;
        console.log(this.data.isMonth)
        if(this.data.isMonth){
            console.log(this.data.hasmore)
        if(t.data.hasmore==false){
            return;
        }
        wx.showToast({
          title: '请稍等...',
          icon:'none'
        })
        e++, t.setData({
            skip:e
        })
     
        t.allRequest(e)
        }else{

             if(t.data.hasnewmore==false){
            return;
        }
              wx.showToast({
          title: '请稍等...',
          icon:'none'
        })
         e = t.data.newskip;
        e++, t.setData({
            newskip:e
        })
        }
    },
    onShareAppMessage: function(t) {
        var e = wx.getStorageSync("nickName"), o ="朋友";
        var uid=wx.getStorageSync("uid");
        if("button" === t.from){
            var a = t.target.dataset.voteid, o = e || "朋友";
            var type=t.target.dataset.type
            var path="/pages/vote_detail/vote_detail?shareFrom=share&uid=";
            if(type==2){
                path="/more/newvote/detail?shareFrom=share&uid="
            }
        return "button" === t.from && console.log(t), {
            title: o + "邀你投一票！",
            path: path + uid + "&tid=" + a,
            success: function(t) {}
        };
    }else{
       return {
        title: o + "邀你投票！为赞同的意见投票,热门话题讨论",
            path: "/pages/index/index",
            success: function(t) {}
        };
    }
    },
    allRequest(skip=1,type=1){
        var that=this
        var promise1 = this.getNewList(skip,type);
        var promise2 =this.getAnswer(type);

        Promise.all([promise1, promise2]).then(function(values) {   
           
            if(values.length>=1){
             
                values[0].forEach(item => {
                    if(values[1]!=undefined){
                    values[1].forEach(ele=>{
                        if(item.objectId==ele.vid){
                            item.answer=ele
                        }
                     
            // item.answerImg= that.getRandomArrayElements(values[2],6)
                    })
                }
                });
               
                    if(type==2){
                    let votes=that.data.toplist
                    that.setData({
                        toplist:votes.concat(values[0]),
                        hidden:!0
                    })
                    }else{
                    let votes=that.data.votes

                    that.setData({
                        votes:votes.concat(values[0]),
                        hidden:!0
                    })
                    }
                }
              
                wx.hideLoading();
            
          

          });
    },
    showImg(t){
        var e = t.currentTarget.dataset.url;
       
        if(!e){return}
        wx.previewImage({
            current: e,
            urls: [ e ]
        });
    },
    getAnswer(type=1){
        let that=this
        let uid=wx.getStorageSync('uid')
        if(!uid){return}
        let param={
            uid:uid
        }
        let attr={
            limit:490,
            order:'-updatedAt'
        }
        var sqltable="vote_answer";
        if(type==2){
            sqltable='vote_detail'
        }
       return new Promise(function(resolve,reject){
        wx.Als.bmobFunc(sqltable, 'all',param,attr).then(res => {
            if(res){
                resolve(res)
            }else{
                resolve([])
                
            }

        })
       }).catch(res=>{
           console.log('oooo')
           reject('vote_answer_is error')
       })

    },
    getNewList(skip=1,table=1){
        var that=this;
        var uid=wx.getStorageSync('uid');
        if(!uid){return}
            var limits =30;
            
      
            var param={
                'like':{
                    k:'uid',
                    v:uid
                },
                notlike:{
                    k:'isdel',
                    v:true
                }
                
            }
          
    

        var attr = {
            'limit': limits,
            'order':'-createdAt',
            skip:skip-1
  
          }
          var sqltable="vote_list";
          if(table==2){
              sqltable='vote_info'
          }
          return new Promise(function(resolve, reject) {
        wx.Als.bmobFunc(sqltable, 'all',param, attr).then(res => {
            console.log("res==")
        console.log(res)
          if (res.length > 0) {
            resolve(res)
         
       
          
            
          }else{
              wx.showToast({
                title: '没有更多~',
                icon:'none'
              })
              if(table==2){
                  that.setData({
                hasnewmore:false
              })
              }else{
   that.setData({
                hasmore:false
              })
              }
           
                
                  reject("vote_list_is error")
            
          }
        
      
        })

    })

    },
    delCard(e){
        var index=e.currentTarget.dataset.index
        var list=this.data.votes
        var vid=e.currentTarget.dataset.voteid;
        if(!vid){return}
        var type=e.currentTarget.dataset.type
        if(type==2){
            var toplist=this.data.toplist
             toplist.splice(index,1);
             this.deleteId(vid,type)
        this.setData({
            toplist:toplist
        })
        }else{

       
        list.splice(index,1);
        this.deleteId(vid)
        this.setData({
            votes:list
        })
         }
    },
    deleteId(attr,type=1){
        if(!attr){return}
        let param={
            isdel:true,
            show:true
        }
        var sqltable='vote_list';
        if(type==2){
            sqltable='vote_info'
        }
        wx.Als.bmobFunc(sqltable, 'get_one', param,attr).then(res => {
            console.log(res)
            wx.showToast({
              title: '删除成功~',
            })
        })
    },
    agree: function(t) {
        var e = t.currentTarget.dataset.id, a = this;
        let info=t.currentTarget.dataset.info;
        let type=t.currentTarget.dataset.type;
        let index=t.currentTarget.dataset.index;
        let answerImg=t.currentTarget.dataset.uimg;
        if(info){
            info=Number(info)
        }
     
        var uid=wx.getStorageSync('uid');
            console.log(info);
          
        if(!e||!uid||this.data.canshow==false){return}
        wx.showToast({
          title: '提交中...',
          icon:'none'
        })
        let param={
            uid:uid,
            vid:e
        }
        let attr={
            limit:1
        }
        this.setData({
            canshow:false
        })
        wx.Als.bmobFunc('vote_answer','all',param,attr).then(res=>{
           
            if(res&&res.length==0){
                a.add_vote(uid,e,info,index,type,answerImg);
               app.addVoteNum(uid)
            }else{
                wx.showToast({
                  title: '已经回答',
                  icon:'none'
                })
            }

        })
        setTimeout(function(res){
            a.setData({
              canshow:true
            })
          },1000);
    },
    update_list(aid,vid,content=1){
let query = wx.Bmob.Query('vote_list');
const pointer = wx.Bmob.Pointer('vote_answer')
const relID = pointer.set(aid)
content=Number(content)
// const relation = wx.Bmob.Relation('vote_answer') // 需要关联的表
// const relID = relation.add([aid,"vid"]) 
query.get(vid).then(res => {
  console.log(res)
  console.log("udpate")
  let c='vote_content'+content;
  let num1=Number(res[c])+1;
  console.log(num1);
  console.log("====")
  let num2=Number(res.group_count)+1;
 res.set('vote_content'+content,num1);
 res.set('group_count',num2);
 res.set('newid',relID); 
   res.save();

}).catch(err => {
  console.log(err)
})
    },
    add_vote(uid,vid,content1='',index=0,type=1,myArr=[]){
        let a=this;
        let content=Number(content1)
        const pointer = wx.Bmob.Pointer('vote_user')
        const poiID = pointer.set(uid)
        let param={
            uid:uid,
            vid:vid,
            content:content,
            userinfo:poiID
        }
        wx.Als.bmobFunc('vote_answer', 'add', param).then(res => {
            var uimg=wx.getStorageSync('uimg')
            var answerImg=myArr
           
           
            if(type==2){
                var votes_new=a.data.votes_new
                var votearr='votes_new['+index+'].answer';
                var vote='votes_new['+index+']';
                var voteinfo=votes_new[index];
                var myanswer='votes_new['+index+'].answerImg';
             
                
            }else{
                var votes=a.data.votes
                var votearr='votes['+index+'].answer';
                var vote='votes['+index+']';
                var voteinfo=votes[index]
                var myanswer='votes['+index+'].answerImg';
            }
            
            voteinfo.group_count=voteinfo.group_count+1;
            var  contentinfo='vote_content'+content;
            voteinfo[contentinfo]= voteinfo[contentinfo]+1;
           
         
            let uid=wx.getStorageSync('uid')
            if(res){
                a.setData({
                    [votearr]:{content:content,uid:uid},
                    [vote]:voteinfo,
                  
                })
                a.update_list(res.objectId,vid,content);
            }
           
          })
    },

    add_list(title,content1,content2,vote_content1=0,vote_content2=0,avatar=''){
        let that=this;
        if(!title||!vote_content2)return;
        var nick_name=wx.getStorageSync('nickName');
   
        var uid=wx.getStorageSync('uid');
        var group_count=Number(vote_content1)+Number(vote_content2)
        let param2={
            title:title
        }
        wx.showLoading({
            title: '添加中...',
          })
          let param={
            uid:uid,
            title:title,
            content1:content1,
            content2:content2,
            group_count:group_count,
            vote_content1:vote_content1,
            vote_content2:vote_content2,
            idlist:[],
            nick_name:nick_name,
            avatar:avatar,
            
          }
        wx.Als.bmobFunc('vote_list','all',param2).then(res=>{
            if(res.length>0){
                return;
            }else{
                wx.Als.bmobFunc('vote_list', 'add', param).then(res => {
                    console.log(res)
                    console.log(res)
                    wx.hideLoading();
                    if(res){
                    
                      wx.showToast({
                        title: '添加成功~',
                      })
              
                    }
                  })
            }
        })
    
      
      
     },

    onCreatePoster(e) {
        let title=e.currentTarget.dataset.title;
        var b1=e.currentTarget.dataset.b1;
        var b2=e.currentTarget.dataset.b2;
        if(b1&&b2&&title){
        var fontSize=42;
        var textinfo="right";
        var bx=100;
        if(b1.length>8||b2.length>8){
            fontSize=30;
            textinfo="center";
            bx=40;
            console.log('b111==')
            if(b2.length>15){
                b2=b2.substring(0,15)+'...'
            }
            if(b1.length>12){
                bx=10;
            }
            if(b1.length>15){
                fontSize=28;
                b1=b1.substring(0,15)+'...'
                var bx=110;
                textinfo="left"
                
            }
        }
        
     
        var e = {
            width: 750,
            height: 1014,
            backgroundColor: "#fff",
            debug: !1,
            renderType: "timeline",
            blocks: [ {
                x: bx,
                y: 320,
                width: 200,
                height: 154,
                borderRadius: 20,
                text: {
                    width: 200,
                    height: 154,
                    lineHeight: 50,
                    textAlign: textinfo,
                    color: "#000",
                    baseLine: "top",
                    fontSize: fontSize,
                    text: b1,
                    lineNum: 3,
                },
                zIndex: 2
            }, {
                x: 440,
                y: 320,
                width: 210,
                height: 154,
                text: {
                    width: 200,
                    height: 154,
                    lineHeight: 50,
                    textAlign: "left",
                    color: "#000",
                    baseLine: "top",
                    fontSize: fontSize,
                    lineNum: 3,
                    text: b2
                },
                zIndex: 2
            } ],
            texts: [ {
                x: 100,
                y: 160,
                width: 550,
                lineHeight: 70,
                text:title,
                textAlign: "center",
                fontSize: 48,
                lineNum: 3,
                color: "#000000",
                baseLine: "middle",
                zIndex: 3
            }, {
                x: 100,
                y: 60,
                width: 550,
                height: 50,
                lineHeight: 50,
                textAlign: "center",
                fontSize: 30,
                text:"话题投票",
                color: "#8d76ff",
                zIndex: 3
            }, {
                x: 279,
                y: 860,
                width: 192,
                height: 20,
                lineHeight: 24,
                textAlign: "center",
                fontSize: 24,
                text: "长按小程序码参与",
                color: "#000000",
                zIndex: 3
            } ],
            images: [ {
                width: 750,
                height: 1014,
                x: 0,
                y: 0,
                url: "/img/poster-bg2.jpg",
                zIndex: 1
            }, {
                width: 60,
                height: 60,
                x: 335,
                y: 390,
                url: "/img/VS.png",
                zIndex: 3
            }, {
                width: 192,
                height: 192,
                x: 279,
                y: 630,
                url: "/img/qrcode.jpeg",
                zIndex: 3
            } ]
        };
     
          Poster.default.create(e);
        }else{
            wx.showToast({
              title: '生成失败',
              icon:'none'
            })
        }
      },
      onPosterFail: function(t) {
        console.error(t);
    },
    onPosterSuccess: function(t) {
        var e = t.detail;
        if(!e){return}
        wx.previewImage({
            current: e,
            urls: [ e ]
        });
    },
    
});